from myweb.settings import STATICFILES_DIRS
from numpy import e
import pandas as pd
from django.http import request as rs
from django.shortcuts import redirect, render
import time,os
from django.core.paginator import Paginator
from PIL import Image
from django.shortcuts import redirect
from django.http import HttpResponse,JsonResponse
import json,re
from django.views.decorators.csrf import csrf_exempt
import re
# Create your views here.
destination=''#记录上传的pdb文件的位置
@csrf_exempt
def upload(request):
    print(request)
    global destination
    file = request.FILES.get("file")
    data = request.POST.get("data")       # 从POST请求中获取其他数据， 提前在formData中定义的
    destination=os.path.join("static/myapp",file.name)
    with open(destination,'wb+') as fp:
        for chunk in file.chunks():# 分块读取二进制文件的方法
            fp.write(chunk)
    return  returnjson()  
def pdbparse(destination):
    # 打开文件
    fp = open(destination,encoding='utf-8')
    list = fp.readlines()
    
    # 存放ATOM123
    atom_list = []
    # 存放HETATM
    hetatm_list = []

    # 得到所有ATOM和HETATM数据
    for i in range(len(list)):
        str = list[i].split()
        if str[0] == "ATOM":
            atom_list.append(str)
        if str[0] == "HETATM":
            if len(str) < 12:
                temp = re.match(r'(\w*\d)(\D*)',str[2]).groups()
            str.insert(3,temp[1])
            str[2] = temp[0]
            hetatm_list.append(str)

    # 数据封装成DataFrame
    atom = pd.DataFrame(atom_list,columns=["类型","原子序号","原子名称","残基名称","链标识符","残疾序列号","x","y","z","占有率","温度因子","元素符号"])
    hetatm = pd.DataFrame(hetatm_list,columns=["类型","原子序号","原子名称","残基名称","链标识符","残疾序列号","x","y","z","占有率","温度因子","元素符号"])
    #atomLabelList: ["类型", "原子序号", "原子名称", "残基名称", "链标识符", "残疾序列号", "原子坐标", "温度因子", "元素符号"],
    fp.close()
    # 返回
    return atom,hetatm

def getatom(request):
    print(request)
    global destination
    need_list = request.GET.getlist('list[]',None)
    need_list.insert(0,'类型')  
    # 解析文件,得到atom所有数据
    data = pdbparse(destination)
    atom = data[0]
    xyz_atom = atom['x']+' '+atom['y']+' '+atom['z']
    atom.drop(['x','y','z'],axis=1)
    atom.insert(6,'原子坐标',xyz_atom)

    # 整合所需列，得到新DataFrame
    atom = atom.loc[:,need_list]
    # print(atom)
    #写入文件
    filename=destination.split('/')[-1].split('.')[0]
    atom.to_csv(f'./static/myapp/ATOM{filename}.csv',encoding='utf-8')
    os.system(f'tar -zcvf ./static/myapp/ATOM{filename}.csv.tar.gz -C ./static/myapp ATOM{filename}.csv') 
    res = {'destination':f'/static/myapp/ATOM{filename}.csv.tar.gz'}
    return HttpResponse(json.dumps(res))

def gethetatm(request):
    global destination
    need_list = request.GET.getlist('list[]',None)
    need_list.insert(0,'类型')  
    # 解析文件,得到hetatm所有数据
    data = pdbparse(destination)
    hetatm = data[1]

    # 将xyz坐标整合
    xyz_hetatm = hetatm['x']+' '+hetatm['y']+' '+hetatm['z']
    hetatm.drop(['x','y','z'],axis=1)
    hetatm.insert(6,'原子坐标',xyz_hetatm)

    # 整合所需列，得到新DataFrame
    hetatm = hetatm.loc[:,need_list]
    # print(hetatm)
    #写入文件
    filename=destination.split('/')[-1].split('.')[0]
    hetatm.to_csv(f'./static/myapp/HETATM{filename}.csv',encoding='utf-8')
    os.system(f'tar -zcvf ./static/myapp/HETATM{filename}.csv.tar.gz -C ./static/myapp HETATM{filename}.csv') 
    res = {'destination':f'/static/myapp/HETATM{filename}.csv.tar.gz'}
    return HttpResponse(json.dumps(res))

def returnjson():

    fp = open(destination,'r',encoding='utf-8')
    list = fp.readlines()

    aa_codes = {
     'ALA':'A', 'CYS':'C', 'ASP':'D', 'GLU':'E',
     'PHE':'F', 'GLY':'G', 'HIS':'H', 'LYS':'K',
     'ILE':'I', 'LEU':'L', 'MET':'M', 'ASN':'N',
     'PRO':'P', 'GLN':'Q', 'ARG':'R', 'SER':'S',
     'THR':'T', 'VAL':'V', 'TYR':'Y', 'TRP':'W'}

    seq = ''
    atom_list = []
    hetatm_list = []
 
    for line in list:
        if line[0:6] == "SEQRES":
            columns = line.split()
            for resname in columns[4:]:
                seq = seq + aa_codes[resname]
        if line[0:4] == "ATOM":
            columns = line.split()
            # print(columns)
            atom_dic = {'category':columns[0],'num':columns[1],'atom_name':columns[2],'residues':columns[3],'chain_identifier':columns[4],'residues_num':columns[5],'atom_lcation':columns[6]+' '+columns[7]+' '+columns[8],'occupation_rate':columns[9],'temperature':columns[10],'element_symbol':columns[11]}
            atom_list.append(atom_dic)
        if line[0:6] == 'HETATM':
            columns = line.split()
            if len(columns) < 12:
                temp = re.match(r'(\w*\d)(\D*)',columns[2]).groups()
                columns.insert(3,temp[1])
                columns[2] = temp[0]
            print(columns)
            hetatm_dic = {'category':columns[0],'num':columns[1],'atom_name':columns[2],'residues':columns[3],'chain_identifier':columns[4],'residues_num':columns[5],'atom_lcation':columns[6]+' '+columns[7]+' '+columns[8],'occupation_rate':columns[9],'temperature':columns[10],'element_symbol':columns[11]}
            hetatm_list.append(hetatm_dic)

    result = {'sequence':seq,'atom':atom_list,'hetatm':hetatm_list}
    fp.close()
    return HttpResponse(json.dumps(result), content_type="application/json")